import {ref} from "vue";
import {IAudioMetadata} from "music-metadata/lib/type";

const remote = window.remote;
const extensions = ['mp3', 'flac', 'aac', 'ogg', 'wav'];
const panelText = ref('点击选择或拖入文件（目录）');
const fileList = ref<File[]>([]);
const loading = ref(true);
const {fs, path: pathUtil} = window.node;

interface File {
    path: string,
    name: string,
    isDirectory: boolean,
    size: number,
    extname: string,
    downloading?: boolean,
    meta?: IAudioMetadata,
    lyric?: string
}

/**
 * 处理拖拽的文件（目录）
 * @param e
 */
const handleDrop = (e: DragEvent) => {
    let files: any[] = Array.from(e.dataTransfer?.files || []);
    files = files.map(({path, name, size}) => {
        const isDirectory = window.$file.isDirectory(path)
        return {
            path,
            name: isDirectory ? '' : name,
            size: isDirectory ? 0 : size,
            isDirectory,
            extname: isDirectory ? '' : pathUtil.extname(path).replace(/^\./, '')
        }
    }).filter(item => {
        return item.isDirectory || extensions.includes(item.extname)
    });
    handleFiles(files);
}
/**
 * 处理点击选择的文件（目录）
 */
const handleClickSelect = () => {
    let files: any[] = remote.showOpenDialogSync({
        title: '选择音乐文件或目录',
        message: '请选择需要下载歌词的音乐文件或目录',
        buttonLabel: '确定',
        filters: [{
            name: '音频文件',
            extensions
        }],
        properties: ['multiSelections', 'openDirectory', 'openFile']
    }) || [];
    files = files.map(mapPath2File);
    handleFiles(files);
}

const mapPath2File = (path: string): File => {
    const {size} = fs.statSync(path);
    const isDirectory = window.$file.isDirectory(path)
    const {name, ext} = pathUtil.parse(path);
    return {
        path,
        name: isDirectory ? '' : name + ext,
        size: isDirectory ? 0 : size,
        isDirectory,
        extname: isDirectory ? '' : ext.replace(/^\./, '')
    }
}

const loadDirs = (dirs: File[], files: File[] = []): File[] => {
    dirs.forEach(dir => {
        const dirFiles = window.node.fs.readdirSync(dir.path).map(file => mapPath2File(pathUtil.join(dir.path, file)));
        const dirs = dirFiles.filter(item => item.isDirectory);
        files.push(...dirFiles.filter(item => !item.isDirectory && extensions.includes(item.extname)));
        loadDirs(dirs, files);
    });
    return files;
};

const uniqueFiles = (files: File[]): File[] => {
    const result: File[] = [];
    files.forEach(item => {
        if (!result.find(file => file.path === item.path)) {
            result.push(item);
        }
    });
    return result;
};

const handleFiles = async (files: File[]) => {
    loading.value = true;
    const dirs = files.filter(item => item.isDirectory);
    files = files.filter(item => !item.isDirectory);
    files.push(...loadDirs(dirs));
    files = uniqueFiles(files);
    fileList.value = files;
    for (let i = 0; i < files.length; i++) {
        let item = files[i];
        item.meta = await window.music.getMusicData(item.path)
    }
    loading.value = false;
};

export {
    panelText,
    handleDrop,
    handleClickSelect,
    fileList,
    File,
    loading
}
